package com.example.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.DepartmentsEntity;
import com.example.mapper.DepartmentsMapper;
import com.example.service.DepartmentsService;
import com.example.utils.ReturnT;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentsServiceImpl implements DepartmentsService {

    @Resource
    private DepartmentsMapper departmentsMapper;

    @Override
    public Object insert(DepartmentsEntity departmentsEntity) {
        if (departmentsEntity == null) {
            return ReturnT.error("参数缺失");
        }
        int result = departmentsMapper.insertDepartment(departmentsEntity);
        return result > 0 ? ReturnT.success() : ReturnT.error("插入失败");
    }

    @Override
    public Object delete(int id) {
        int ret = departmentsMapper.deleteById(id);
        return ret > 0 ? ReturnT.success() : ReturnT.error("删除失败");
    }

    @Override
    public Object update(DepartmentsEntity departmentsEntity) {
        int ret = departmentsMapper.updateById(departmentsEntity);
        return ret > 0 ? ReturnT.success() : ReturnT.error("修改失败");
    }

    @Override
    public DepartmentsEntity load(int id) {
        return departmentsMapper.selectById(id);
    }

    @Override
    public Map<String, Object> pageList(int offset, int pagesize) {
        List<DepartmentsEntity> pageList = departmentsMapper.pageList(offset, pagesize);
        int totalCount = departmentsMapper.pageListCount(offset, pagesize);

        // result
        Map<String, Object> result = new HashMap<>();
        result.put("pageList", pageList);
        result.put("totalCount", totalCount);

        return result;
    }

    /**
     * 通过部门code获取部门信息
     *
     * @param departmentCode
     * @return
     */
    @Override
    public ReturnT<List<DepartmentsEntity>> selectByDepartmentCode(String departmentCode) {
        QueryWrapper<DepartmentsEntity> qw = new QueryWrapper<>();
        if (departmentCode != null && !departmentCode.isEmpty()) {
            qw.eq("department_code", departmentCode);
        }
        List<DepartmentsEntity> departmentsEntities = departmentsMapper.selectList(qw);

        return ReturnT.success(departmentsEntities);
    }
}